package Demo91;


import java.util.LinkedList;
import java.util.Queue;

/**
 * 01 矩阵
 * https://leetcode.cn/problems/2bCMpM/description/
 */

class Solution {
    int m,n;
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    public int[][] updateMatrix(int[][] mat) {
        // 将起点放入队列中
        m = mat.length; n = mat[0].length;
        Queue<int[]> q = new LinkedList<>();
        boolean[][] vis = new boolean[m][n];
        int[][] bast = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n;j++) {
                if(mat[i][j] == 0) {
                    q.add(new int[] {i,j});
                    vis[i][j] = true;
                    bast[i][j] = 0;
                }
            }
        }
        int stap = 0;
        // 一层一层遍历
        while(!q.isEmpty()) {
            stap++;
            int sz = q.size();
            while(sz-- != 0) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for(int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
                        bast[x][y] = stap;
                        vis[x][y] = true;
                        q.add(new int[] {x,y});
                    }
                }
            }
        }
        return bast;
    }
}